<h2>Why is this an issue?</h2>
<p>When writing code, it is quite common to test patterns against string ends. For a long time, JavaScript did not provide proper support for this use
case. As a result, developers have been relying on various programming subtleties to check the start or end of a string. Examples are getting the
index of a substring, slicing the beginning of a string, extracting a substring from the head, matching a regular expression beginning or ending with
a pattern, and so on.</p>
<p>While these approaches are all technically valid, they look more like hacking than anything else, blur the developer’s intent, but more importantly
affect code readability.</p>
<p>Since ES2015, JavaScript provides <code>String#startsWith</code> and <code>String#endsWith</code>, which are the preferred ways to test patterns
against string ends.</p>
<h2>How to fix it</h2>
<p>One should use <code>String#startsWith</code> to check the start of a string and <code>String#endsWith</code> to check the end.</p>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<pre>
const str = 'abc';

str[0] === 'a';
str.charAt(0) === 'a';
str.indexOf('abc') === 0;
str.slice(0, 3) === 'abc';
str.substring(0, 3) === 'abc';
str.match(/^abc/) != null;
/^abc/.test(str);
</pre>
<h4>Compliant solution</h4>
<pre>
str.startsWith('abc');
</pre>
<h4>Noncompliant code example</h4>
<pre>
const str = 'abc';

str[str.length - 1] === 'c';
str.charAt(str.length - 1) === 'c';
str.lastIndexOf('abc') === str.length - 3;
str.slice(-3) === 'abc';
str.substring(str.length - 3) === 'abc';
str.match(/abc$/) != null;
/abc$/.test(str);
</pre>
<h4>Compliant solution</h4>
<pre>
str.endsWith('abc');
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
  <li> <a href="https://typescript-eslint.io/">typescript-eslint</a> - Rule <a
  href="https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/prefer-string-starts-ends-with.mdx">prefer-string-starts-ends-with</a> </li>
  <li> MDN web docs - <a
  href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith">String#startsWith</a> </li>
  <li> MDN web docs - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith">String#endsWith</a>
  </li>
</ul>
